package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class SocketContentHandle {
	public static Document getSiteContentBySocket(String site, String url)
                        throws UnknownHostException, IOException {			
		// Create connection to site by socket
		// remote host
//    		Random random = new Random();		
//		Socket socket = new Socket(site, 80, InetAddress.getByName("184.107.59.40"),
//				random.nextInt(1000) + 30000);
		
		//local host
		Socket socket = new Socket(site, 80);
		
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				socket.getOutputStream()));

		writer.write("GET " + url + " HTTP/1.1\r\n");
		writer.write("Host: " + "www." + site + "\r\n");
		writer.write("Referer: http://google.com\r\n");
		writer.write("User-Agent:	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1\r\n");
		writer.write("Connection:	Close\r\n");
		writer.write("\r\n\r\n");
		writer.flush();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				socket.getInputStream(), "UTF-8"));
		String content = "";		
		while (true) {
			String str = reader.readLine();
			if (str == null)
				break;			
			content += str;                        
		}		
		Document doc = Jsoup.parse(content);
		reader.close();
		writer.close();
		socket.close();		
		return doc;		
	}
}
